package com.bluezone.dec.system.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bluezone.dec.common.annotation.AuthPermission;
import com.bluezone.dec.configuration.AppConfig;
import com.bluezone.dec.uac.UACServiceFactory;
import com.bluezone.dec.utils.HttpContextUtils;
import com.c503.sc.utils.response.ResultMessage;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import sc.c503.authclient.model.ApiUserEntity;
import sc.c503.authclient.model.SysRscOperEntity;
import sc.c503.authclient.service.splitImpl.ApiRelationService;

import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    AppConfig appConfig;

    @Autowired
    StringRedisTemplate redisTemplate;

    /**
     * 登陆
     *
     * @param name 账号
     * @param pwd  密码
     * @return
     */
    public JSONObject login(String name, String pwd) {
        ResultMessage resultMessage = UACServiceFactory.apiLoginService().login(name, pwd);
        boolean loginStatus = resultMessage.getCode() == 0;
        if (loginStatus) {
            return saveUserInfo(JSON.toJavaObject((JSON) resultMessage.getData(), ApiUserEntity.class));
        }
        return null;
    }

    /**
     * 保存用户信息（权限和基本信息）
     *
     * @param user
     */
    public JSONObject saveUserInfo(ApiUserEntity user) {
        if (user == null) {
            return null;
        }
        String token = user.getToken();
        JSONObject data = new JSONObject();
        data.put("account", user.getAccount() + "");
        data.put("sex", user.getSex() + "");
        data.put("address", user.getCommAddress() + "");
        data.put("name", user.getName() + "");
        data.put("userId", user.getId() + "");
        data.put("token", token + "");
        //获取权限
        List<JSONObject> rights = new ArrayList<>();

        ApiRelationService svc = UACServiceFactory.apiRelationService(token);
        List<SysRscOperEntity> rList = svc.getRscByToken();
        for (SysRscOperEntity entity : rList) {
            JSONObject object = new JSONObject();
            object.put("moduleId", entity.getMid());
            object.put("modulePid", entity.getMpid());
            object.put("moduleName", entity.getMname());
            object.put("moduleCode", entity.getMtarget());
            object.put("moduleUrl", entity.getMurl());
            object.put("functionId", entity.getFid());
            object.put("functionName", entity.getFname());
            object.put("functionCode", entity.getFidentifying());
            rights.add(object);
        }
        data.put("rights", rights);
        String key = new StringBuilder(appConfig.getApiKeyUserId()).append("-").append(token).toString();
        redisTemplate.opsForValue().set(key, JSON.toJSONString(data), appConfig.getExpired(),
                TimeUnit.MINUTES);
        return data;
    }

    /**
     * 获取登录用户信息
     *
     * @return JSONObject
     */
    public JSONObject getUserInfo() {
        String token = HttpContextUtils.getHttpServletRequest().getHeader(appConfig.keyName());
        if (token == null || token.isEmpty()) {
            return null;
        }
        String key = new StringBuilder(appConfig.getApiKeyUserId()).append("-").append(token).toString();
        String val = redisTemplate.opsForValue().get(key);
        return JSONObject.parseObject(val);
    }

    /**
     * 从缓存中清除用户信息
     */
    public void deleteUserInfo() {
        String token = HttpContextUtils.getHttpServletRequest().getHeader(appConfig.keyName());
        if (token == null) {
            return;
        }
        String key = new StringBuilder(appConfig.getApiKeyUserId()).append("-").append(token).toString();
        String val = redisTemplate.opsForValue().get(key);
        if (!Strings.isNullOrEmpty(val)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 权限验证
     *
     * @param handler
     * @return
     */
    public boolean authPermission(Object handler) {
        // 获取用户信息
        JSONObject userInfo = getUserInfo();
        if (userInfo != null) {
            // 获取权限集合
            List<JSONObject> rights = (List<JSONObject>) userInfo.get("rights");
            Set<String> permissions = new HashSet<>();
            for (JSONObject obj : rights) {
                String permiss = (String) obj.get("functionCode");
                permissions.add(permiss);
            }
            // 将handler强转为HandlerMethod
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 从方法处理器中获取出要调用的方法
            Method method = handlerMethod.getMethod();
            // 获取注解
            AuthPermission auth = method.getAnnotation(AuthPermission.class);
            if (auth == null) {
                return true;
            }
            if (!permissions.isEmpty()) {
                // 验证权限
                return permissions.contains(auth.value());
            }
        }
        return false;
    }

}
